package cn.edu.zime.tjh.gui;

import cn.edu.zime.tjh.handler.EchoServerHandler;
import cn.edu.zime.tjh.server.EchoServer;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.stage.Stage;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Timer;
import java.util.TimerTask;

public class ServerGUIApp extends Application {
    private TextArea logArea;
    private TextField portField;
    private Button startButton;
    private Button stopButton;
    private Label statusLabel;
    private Label clientCountLabel;
    
    // 消息发送区域
    private TextField broadcastField;
    private Button broadcastButton;
    private ListView<String> clientListView;
    private TextField messageField;
    private Button sendToClientButton;
    
    private EchoServer server;
    private Timer refreshTimer;
    private ObservableList<String> clientList;
    
    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("IoT Communication Server Manager");
        
        createUI(primaryStage);
        setupEventHandlers();
        startRefreshTimer();
        
        primaryStage.setOnCloseRequest(e -> {
            stopServer();
            if (refreshTimer != null) {
                refreshTimer.cancel();
            }
            Platform.exit();
        });
        
        primaryStage.show();
    }
    
    private void createUI(Stage primaryStage) {
        BorderPane root = new BorderPane();
        root.setPadding(new Insets(10));
        
        // 顶部 - 服务器控制
        VBox topBox = new VBox(10);
        
        HBox serverControlBox = new HBox(10);
        serverControlBox.getChildren().addAll(
            new Label("Port:"),
            portField = new TextField("8080"),
            startButton = new Button("Start Server"),
            stopButton = new Button("Stop Server")
        );
        
        portField.setPrefWidth(80);
        stopButton.setDisable(true);
        
        statusLabel = new Label("Status: Server Stopped");
        statusLabel.setStyle("-fx-text-fill: red;");
        
        clientCountLabel = new Label("Connected Clients: 0");
        
        topBox.getChildren().addAll(serverControlBox, statusLabel, clientCountLabel);
        
        // 中间 - 日志区域
        VBox centerBox = new VBox(5);
        centerBox.getChildren().addAll(
            new Label("Server Log:"),
            logArea = new TextArea()
        );
        
        logArea.setEditable(false);
        logArea.setPrefRowCount(15);
        logArea.setWrapText(true);
        
        // 右侧 - 客户端管理和消息发送
        VBox rightBox = new VBox(10);
        rightBox.setPrefWidth(300);
        
        // 广播消息
        VBox broadcastBox = new VBox(5);
        broadcastBox.getChildren().addAll(
            new Label("Broadcast Message:"),
            broadcastField = new TextField(),
            broadcastButton = new Button("Broadcast to All")
        );
        broadcastButton.setDisable(true);
        
        // 客户端列表
        VBox clientBox = new VBox(5);
        clientList = FXCollections.observableArrayList();
        clientListView = new ListView<>(clientList);
        clientListView.setPrefHeight(150);
        
        clientBox.getChildren().addAll(
            new Label("Connected Clients:"),
            clientListView
        );
        
        // 发送给特定客户端
        VBox messageBox = new VBox(5);
        messageBox.getChildren().addAll(
            new Label("发送给选中客户端:"),
            messageField = new TextField(),
            sendToClientButton = new Button("发送消息")
        );
        sendToClientButton.setDisable(true);
        
        rightBox.getChildren().addAll(broadcastBox, clientBox, messageBox);
        
        root.setTop(topBox);
        root.setCenter(centerBox);
        root.setRight(rightBox);
        
        Scene scene = new Scene(root, 900, 600);
        primaryStage.setScene(scene);
    }
    
    private void setupEventHandlers() {
        startButton.setOnAction(e -> startServer());
        stopButton.setOnAction(e -> stopServer());
        broadcastButton.setOnAction(e -> broadcastMessage());
        sendToClientButton.setOnAction(e -> sendMessageToClient());
        
        broadcastField.setOnAction(e -> broadcastMessage());
        messageField.setOnAction(e -> sendMessageToClient());
    }
    
    private void startServer() {
        String portText = portField.getText().trim();
        
        if (portText.isEmpty()) {
            showLog("请输入端口号", "错误");
            return;
        }
        
        try {
            int port = Integer.parseInt(portText);
            
            server = EchoServer.getInstance();
            
            // 在新线程中启动服务器
            new Thread(() -> {
                try {
                    server.start(port);
                } catch (Exception ex) {
                    Platform.runLater(() -> {
                        showLog("启动服务器失败: " + ex.getMessage(), "错误");
                        resetServerControls();
                    });
                }
            }).start();
            
            Platform.runLater(() -> {
                startButton.setDisable(true);
                stopButton.setDisable(false);
                broadcastButton.setDisable(false);
                sendToClientButton.setDisable(false);
                portField.setDisable(true);
                statusLabel.setText("状态: 服务器运行中，端口 " + port);
                statusLabel.setStyle("-fx-text-fill: green;");
                showLog("服务器已在端口 " + port + " 启动", "系统");
            });
            
        } catch (NumberFormatException ex) {
            showLog("无效的端口号", "错误");
        }
    }
    
    private void stopServer() {
        if (server != null) {
            server.stop();
        }
        resetServerControls();
        showLog("服务器已停止", "系统");
    }
    
    private void resetServerControls() {
        Platform.runLater(() -> {
            startButton.setDisable(false);
            stopButton.setDisable(true);
            broadcastButton.setDisable(true);
            sendToClientButton.setDisable(true);
            portField.setDisable(false);
            statusLabel.setText("状态: 服务器已停止");
            statusLabel.setStyle("-fx-text-fill: red;");
            clientList.clear();
            clientCountLabel.setText("已连接客户端: 0");
        });
    }
    
    private void broadcastMessage() {
        String message = broadcastField.getText().trim();
        if (message.isEmpty()) {
            return;
        }
        
        EchoServerHandler.broadcastMessage(message);
        showLog("Broadcasted: " + message, "BROADCAST");
        broadcastField.clear();
    }
    
    private void sendMessageToClient() {
        String selectedClient = clientListView.getSelectionModel().getSelectedItem();
        String message = messageField.getText().trim();
        
        if (selectedClient == null) {
            showLog("Please select a client", "ERROR");
            return;
        }
        
        if (message.isEmpty()) {
            return;
        }
        
        EchoServerHandler.sendMessageToClient(selectedClient, message);
        showLog("Sent to " + selectedClient + ": " + message, "MESSAGE");
        messageField.clear();
    }
    
    private void startRefreshTimer() {
        refreshTimer = new Timer(true);
        refreshTimer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                Platform.runLater(() -> {
                    updateClientList();
                    updateClientCount();
                });
            }
        }, 1000, 2000); // 每2秒刷新一次
    }
    
    private void updateClientList() {
        String[] clients = EchoServerHandler.getAllClientIds();
        clientList.clear();
        clientList.addAll(clients);
    }
    
    private void updateClientCount() {
        int count = EchoServerHandler.getClientCount();
        clientCountLabel.setText("Connected Clients: " + count);
    }
    
    public void showLog(String message, String type) {
        Platform.runLater(() -> {
            String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss"));
            String formattedMessage = String.format("[%s] %s: %s\n", timestamp, type, message);
            logArea.appendText(formattedMessage);
        });
    }
    
    public static void main(String[] args) {
        launch(args);
    }
}